package com.superzqb.asus.superzqbFragment.superzqbSave;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.baoyz.widget.PullRefreshLayout;
import com.superzqb.asus.Api.SaveApi;
import com.superzqb.asus.superzqb.R;
import com.superzqb.asus.superzqbFragment.superzqbSave.Adapter.GoodsListAdapter;
import com.superzqb.asus.superzqbFragment.superzqbSave.Bean.GoodsListBean;
import com.superzqb.asus.superzqbUtil.Url;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class GoodsList extends Activity implements View.OnClickListener {
    private SharedPreferences sp;
    private ImageView back;
    private ListView lv;
    private int lastItem;
    private int listSize;
    private int pagenum = 1;
    private GoodsListAdapter adapter;
    private List<GoodsListBean> listAll;
    private PullRefreshLayout layout;
    int uid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_list);
        initView();
        listAll = new ArrayList<>();
        adapter = new GoodsListAdapter(GoodsList.this, listAll);
        lv.setAdapter(adapter);
        layout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                layout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        layout.setRefreshing(false);
                        getLv();
                    }
                }, 2000);
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                adapter.changeColor(position);
                adapter.notifyDataSetInvalidated();
                GoodsListBean item = (GoodsListBean) parent.getItemAtPosition(position);
                dialog(Integer.valueOf(item.getAdd_id()));

            }
        });
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == 0) {
                    if (lastItem == listSize) {
                        pagenum++;
                        Toast.makeText(GoodsList.this,
                                "加载第" + pagenum + "页",
                                Toast.LENGTH_SHORT).show();
                        getLv();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                lastItem = lv.getLastVisiblePosition();

            }
        });
    }

    private void getLv() {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(new Url().getBase_url())
                .build();
        SaveApi api = retrofit.create(SaveApi.class);
        Call<List<GoodsListBean>> call = api.getBuyGoodsList(pagenum, uid);
        call.enqueue(new Callback<List<GoodsListBean>>() {
            @Override
            public void onResponse(Call<List<GoodsListBean>> call, Response<List<GoodsListBean>> response) {
                if (response.isSuccessful()) {
                        List<GoodsListBean> list = response.body();
                        if(list!=null){
                        listAll.addAll(list);
                        listSize = listAll.size() - 1;
                        adapter.setList(listAll);
                        adapter.notifyDataSetChanged();
                    }else{
                            listAll.clear();
                            listSize = 0;
                            adapter.setList(listAll);
                            adapter.notifyDataSetChanged();
                        }
                }

            }

            @Override
            public void onFailure(Call<List<GoodsListBean>> call, Throwable throwable) {
                  Toast.makeText(GoodsList.this,"正在查找，请稍后",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initView() {
        layout = (PullRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        sp = getSharedPreferences("uinfo", GoodsList.MODE_PRIVATE);
        uid = Integer.valueOf(sp.getString("uid", null));
        lv = (ListView) findViewById(R.id.listView);
        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    private void dialog(final int id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("是否添加?"); //设置内容
      /*  builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可*/
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {

                //  Toast.makeText(GoodsList.this, "确认" + which, Toast.LENGTH_SHORT).show();
                Retrofit retrofit = new Retrofit.Builder()
                        .addConverterFactory(ScalarsConverterFactory.create())
                        .baseUrl(new Url().getBase_url())
                        .build();
                SaveApi api = retrofit.create(SaveApi.class);
                Call<String> call = api.changeStatus(id);
                call.enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        if (response.isSuccessful()) {
                            String tmp = response.body();
                            if (tmp.equals("success"))
                            {
                                Toast.makeText(GoodsList.this, "添加成功!", Toast.LENGTH_SHORT).show();
                                listAll.clear();
                                getLv();
                            }
                            else
                                Toast.makeText(GoodsList.this, "添加失败!", Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable throwable) {
                           Toast.makeText(GoodsList.this,"添加失败!",Toast.LENGTH_SHORT).show();
                    }
                });
                dialog.dismiss(); //关闭dialog
            }

        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // Toast.makeText(GoodsList.this, "取消" + which, Toast.LENGTH_SHORT).show();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        listAll.clear();
        getLv();
    }
}
